﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Configuration;
using TireService.Data;

namespace TireService.Web.WebHooks
{
    public partial class UpdateCustomer : System.Web.UI.Page
    {
        private int _NewCustomerId = 0;
        private int _OldCustomerId = 0;
        private int _AgreementNumber = 0;
        
        protected void Page_Load(object sender, EventArgs e)        
        {            
            if (Request.QueryString["invoiceno"] != null)            
            {                
                // Get agreement number for e-conomic and check that request can be authorized
                _AgreementNumber = int.Parse(Request.QueryString["AN"]);

                if (_AgreementNumber == int.Parse(ConfigurationSettings.AppSettings["EcoAgreementNumber"]))
                {
                    //a customer has been updated in e-conomic - get id
                    _NewCustomerId = int.Parse(Request.QueryString["NEWNUMBER"]);
                    _OldCustomerId = int.Parse(Request.QueryString["OLDNUMBER"]);

                    //spawn thread to handle work as the actual work will take some time
                    //and e-conomic needs an answer that we have received the WebHook
                    Thread t = new Thread(SynchronizeCustomer);
                    t.Start();
                }
                else
                {
                    // Nothing - request is not authorized
                    // Maybe log request...
                }

                                       
            }        
        }

        /// <summary>
        /// Update/synkronise customer/debtor with e-conomics (E-conomic is the MASTER)
        /// </summary>
        private void SynchronizeCustomer()
        { 
            // Update customer based on E-conomic
            // Check if debtor already exists
            if (_NewCustomerId != _OldCustomerId)
            {
                // Nothing happens
            }
            else
            {
                // Update existing customer

                TireServiceDB db = new TireServiceDB();

                Customer customer = db.GetCustomer(_NewCustomerId);

                if (customer != null)
                {
                    EconomicInterface ecoInterface = new EconomicInterface();

                    // Update debtor based on e-conomic values
                    ecoInterface.UpdateDebtorBasedOnEconomic(customer, db, false);                   
                }
                else
                {
                    // Nothing happens - customer not found
                }
                
            }
        }
    }
}